package com.onetech.adrewards.free.apicall;

import static jp.co.CAReward_Media.CARMIntent.LOGTAG;

import java.util.List;

import jp.co.CAReward_Media.CARMCommon;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ZuZuCARMWebViewClient extends WebViewClient{

	/** アプリ内ブラウザ(スポンサー一覧ページ)対象ドメイン*/
	private static final String MYDOMAIN = "car.mobadme.jp";
//	private static final String MYDOMAIN = "ajmp.jp";
	private static final String MYDOMAIN2 = "ad.mobadme.jp";
	private static final String UPMDOMAIN = "upm.mobadme.jp";
	/** ProgressDialog*/
	private View mPdialog = null;
	/** Activity*/
	private Activity mActivity = null; 

	private String mLoadingMsg = "";
	/** ユーザポイント管理利用フラグ */
	private boolean mUsePoint = false;

	/** NoSDKURL **/
	private final String NO_SDK_URL = "-nosdk";
	private static String cid = null;
	private final String DETAIL_PHP_NAME = "detail.php";
	private final String get_m_id;
	private final String get_m_owner_id;
	private final String get_user_id;
	private final String get_platform_id;
	private final String get_api_key;
	private final String get_app_key;
	private final String get_timeout;
	
	/**
	 * コンストラクタです。<br>
	 * @param activity Activity
	 *
	 */
	public ZuZuCARMWebViewClient (Activity activity, String loading_msg, String get_m_id, 
			String get_m_owner_id, String get_user_id, String get_platform_id, 
			String get_api_key, String get_app_key, String get_timeout,View progressBar) {
		
		super();
		mActivity = activity;
		mLoadingMsg = loading_msg;
		this.mPdialog=progressBar;
		this.get_m_id = get_m_id;
		this.get_m_owner_id = get_m_owner_id;
		this.get_user_id = get_user_id;
		this.get_platform_id = get_platform_id;
		this.get_api_key = get_api_key;
		this.get_app_key = get_app_key;
		this.get_timeout = get_timeout;
	}

	/**
	 * ダイアログを消去します。<br>
	 *
	 */
	public void dismissDialog() {
    	if (mPdialog != null) {
    	    try {
    	    	mPdialog.setVisibility(View.GONE);
    	    } catch (Exception e) {
    	    	e.printStackTrace();
    	    }
    		mPdialog = null;
    	}
    }

    /**
     * ページ読み込み開始時の処理を行います。<br>
	 * @param view WebView
	 * @param url  URL
	 * @param　favicon　FAVICON
     */
	@Override
	public void onPageStarted(WebView view, String url, Bitmap favicon) {
		// ダイアログ表示
		//this.dismissDialog();
//		mPdialog = new ProgressDialog(mActivity);
//		mPdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//		mPdialog.setMessage(mLoadingMsg);
//		mPdialog.show();
		if(mPdialog!=null){
			mPdialog.setVisibility(View.VISIBLE);
		}

	}
	
    /**
     * ページの読み込み終了時の処理を行います。<br>
	 * @param view WebView
	 * @param url  URL
     */
	@Override
	public void onPageFinished(WebView view, String url) {
		//super.onPageFinished(view, url);
		this.dismissDialog();
	}


    /**
     * ページ読み込み時の処理を行います。<br>
     * リクエスト先のドメインをみて起動するブラウザ(アプリ内ブラウザ/標準ブラウザ)を判定します。<br>
	 * @param view WebView
	 * @param url  URL
     */
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {

		if (url.indexOf(DETAIL_PHP_NAME) != -1) {
			cid = getCid(url);
			Log.d(LOGTAG, "CID:" + cid);
		}
		
		if (url.indexOf(NO_SDK_URL) != -1) {
			url = url.replaceAll(NO_SDK_URL, "");
			Log.d(LOGTAG, url);
			if (this.isInstalled(url, view.getContext())) {
				this.notice_action(cid);
			}
		}
		
		// 別ドメインへのリクエストで無ければアプリ内ブラウザで表示
		if (Uri.parse(url).getHost().equals(MYDOMAIN)) {
			return false;
		}
		// ポイント管理利用判定
		if (mUsePoint == true){
			if (Uri.parse(url).getHost().equals(UPMDOMAIN)) {
				return false;
			}
		}

		// マーケットアプリを選択させるため外部ドメインへは標準ブラウザで開く
		this.dismissDialog();
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
	    try {
			mActivity.startActivity(intent);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return true;
	}
	/**
	 * ポイント管理を利用する場合に、インスタンス生成後
	 * すぐに呼び出すこと
	 */
	public void usePointManage(){
		mUsePoint = true;
	}
	/**
	 * URLスキーム存在チェック
	 * @param url_scheme
	 * @return boolean
	 */
	public boolean isInstalled(String url_scheme, Context context) {
		
		PackageManager pm = context.getPackageManager();
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri uri = Uri.parse(url_scheme + "://");
		intent.setData(uri);
		List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
		if(list.size() > 0) {
			Log.d(LOGTAG, "isInstalled:true");
			return true;
		}
		Log.d(LOGTAG, "isInstalled:false");
		return false;
	}
	
	private String getCid(String url) {
		
		String tmp = url.split("ad=")[1];
		
		tmp = tmp.split("&")[0];
		
		return tmp;
	}
	
	/**
	 * 自動成果通知
	 * @param c_id
	 * @return String
	 */
	 public String notice_action(String c_id) {

		// 戻り値（成功：1/失敗：空）
		String notice_status = "";
		CARMCommon mcomm = new CARMCommon();
		 
		// アフィリエイトID取得
		Log.d(LOGTAG, "api:" + get_api_key);
		Log.d(LOGTAG, "user_id:" + get_user_id);
		Log.d(LOGTAG, "mid:" + get_m_id);
		Log.d(LOGTAG, "cid:" + c_id);
		Log.d(LOGTAG, "timeout:" + get_timeout);
		String af_id = mcomm.getAfid(get_api_key, get_user_id, get_m_id, c_id, Integer.parseInt(get_timeout));
		if(af_id.trim().length() <= 0) return notice_status;
		 
		String strLog = "";
		 
		// UUID
		String[] uuid = null;

		// SharedPreferencesよりuuid取得
		String spf_uuid[] = null;
		spf_uuid = mcomm.getUuidSpf(mActivity, get_app_key);
		 
		// TTよりuuid取得
		 String http_uuid[] = null;
		 http_uuid = mcomm.getUuidHttp(get_m_owner_id, get_user_id, get_platform_id, get_app_key, Integer.parseInt(get_timeout));
		 
		// SharedPreferences, TT共に値がない場合
		if(spf_uuid == null && http_uuid == null) {
			
			// uuid新規採番
			uuid = mcomm.getUuid(get_app_key, Integer.parseInt(get_timeout));
			// SharedPreferences登録
			mcomm.setUuidSpf(mActivity, uuid[0]);
			// TT登録
			mcomm.setUuidHttp(get_m_owner_id, get_user_id, get_platform_id, uuid[0], uuid[3], Integer.parseInt(get_timeout));

		} else {
			uuid = null;
			// TT, SharedPreferences共に値がある場合 
			if((http_uuid != null && http_uuid.length > 3) && (spf_uuid != null && spf_uuid.length > 3)) {
				
				// 値が異なる場合
				if(!http_uuid[0].equals(spf_uuid[0])) {
				
					// TTの方が日付が古い
					if(Long.parseLong(http_uuid[3]) < Long.parseLong(spf_uuid[3])) {
					
						// SharedPreferences更新
						mcomm.setUuidSpf(mActivity, http_uuid[0]);
						uuid = new String[4];
						uuid[0] = http_uuid[0];
						uuid[1] = http_uuid[1];
						uuid[2] = http_uuid[2];
						uuid[3] = http_uuid[3];
						
					// SharedPreferencesの方が日付が古い
					} else {
					
						// TT更新
						mcomm.setUuidHttp(get_m_owner_id, get_user_id, get_platform_id, spf_uuid[0], spf_uuid[3], Integer.parseInt(get_timeout));
						uuid = new String[4];
						uuid[0] = spf_uuid[0];
						uuid[1] = spf_uuid[1];
						uuid[2] = spf_uuid[2];
						uuid[3] = spf_uuid[3];
					}
					
				// 値が同じ場合
				} else {
					uuid = new String[4];
					uuid[0] = http_uuid[0];
					uuid[1] = http_uuid[1];
					uuid[2] = http_uuid[2];
					uuid[3] = http_uuid[3];
				}
				
			// TT のみ値がある場合
			} else if((http_uuid != null && http_uuid.length > 3)) {
				
				// SharedPreferences登録
				mcomm.setUuidSpf(mActivity, http_uuid[0]);
				uuid = new String[4];
				uuid[0] = http_uuid[0];
				uuid[1] = http_uuid[1];
				uuid[2] = http_uuid[2];
				uuid[3] = http_uuid[3];

			// SharedPreferences のみ値がある場合
			} else if((spf_uuid != null && spf_uuid.length > 3)) {
				
				// TT登録
				mcomm.setUuidHttp(get_m_owner_id, get_user_id, get_platform_id, spf_uuid[0], spf_uuid[3], Integer.parseInt(get_timeout));
				uuid = new String[4];
				uuid[0] = spf_uuid[0];
				uuid[1] = spf_uuid[1];
				uuid[2] = spf_uuid[2];
				uuid[3] = spf_uuid[3];
			}				
		}
		
		if(uuid != null && uuid.length > 0) strLog += "uuid:" + String.valueOf(uuid[0]) + "¥n";
		if(uuid != null && uuid.length > 3) strLog += "uuid_date:" + String.valueOf(uuid[3]) + "¥n";
		
		strLog = "";
		
		if(uuid == null) return notice_status;
		
		// 成果通知
		if(mcomm.getAction(c_id, af_id, uuid[0], Integer.parseInt(get_timeout))) {
			 // 正常終了
			 notice_status = "1";
		}
		 return notice_status;			
	 }
}